<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>点餐系统 - 客户端</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <h1>点餐系统</h1>

    <!-- 菜品展示 -->
    <h2>菜品列表</h2>
    <div class="row" id="dish-list">
        <!-- 菜品将通过 JavaScript 动态加载 -->
    </div>

    <!-- 购物车 -->
    <h2>购物车</h2>
    <ul class="list-group mb-3" id="cart-list">
        <!-- 购物车内容将通过 JavaScript 动态加载 -->
    </ul>
    <button id="place-order" class="btn btn-success">下单</button>

    <!-- 订单状态 -->
    <h2>订单状态</h2>
    <ul class="list-group" id="order-list">
        <!-- 订单状态将通过 JavaScript 动态加载 -->
    </ul>
</div>

<script>
    // 全局变量
    let dishes = []; // 菜品列表
    let cart = [];   // 购物车
    let orders = []; // 订单列表

    setupWebSocket();
    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', async () => {
        await fetchDishes();
        await fetchOrders();
        renderDishes();
        renderCart();
        renderOrders();
    });

    // 获取菜品列表
    async function fetchDishes() {
        const response = await fetch('api/dish/index');
        const data = await response.json();
        dishes = data.data;
    }

    // 获取订单列表
    async function fetchOrders() {
        const response = await fetch('api/order/index');
        const data = await response.json();
        orders = data.data;
    }

    // 渲染菜品列表
    function renderDishes() {
        const dishList = document.getElementById('dish-list');
        dishList.innerHTML = ''; // 清空现有内容

        dishes.forEach(dish => {
            const dishCard = document.createElement('div');
            dishCard.className = 'col-md-4 mb-3';

            dishCard.innerHTML = `
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">${dish.name}</h5>
                            <p class="card-text">${dish.description}</p>
                            <p class="card-text">价格: ${dish.price} 元</p>
                            <input type="number" id="quantity-${dish.id}" min="1" class="form-control mb-2" placeholder="数量" value="1">
                            <button onclick="addToCart(${dish.id})" class="btn btn-primary">加入购物车</button>
                        </div>
                    </div>
                `;

            dishList.appendChild(dishCard);
        });
    }

    // 加入购物车
    function addToCart(dishId) {
        const quantity = parseInt(document.getElementById(`quantity-${dishId}`).value);
        const dish = dishes.find(d => d.id === dishId);

        const existingItem = cart.find(item => item.dish.id === dishId);
        if (existingItem) {
            existingItem.quantity += quantity;
        } else {
            cart.push({ dish, quantity });
        }

        renderCart();
    }

    // 渲染购物车
    function renderCart() {
        const cartList = document.getElementById('cart-list');
        cartList.innerHTML = ''; // 清空现有内容

        cart.forEach(item => {
            const cartItem = document.createElement('li');
            cartItem.className = 'list-group-item';

            cartItem.innerHTML = `
                    ${item.dish.name} - ${item.quantity} 份
                    <button onclick="removeFromCart(${item.dish.id})" class="btn btn-danger btn-sm float-end">移除</button>
                `;

            cartList.appendChild(cartItem);
        });
    }

    // 从购物车移除
    function removeFromCart(dishId) {
        cart = cart.filter(item => item.dish.id !== dishId);
        renderCart();
    }

    // 下单
    document.getElementById('place-order').addEventListener('click', async () => {
        const orderData = {
            user_id: 1, // 假设用户 ID 为 1
            dishes: cart.map(item => ({ id: item.dish.id, quantity: item.quantity }))
        };

        const response = await fetch('api/order/store', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(orderData)
        });

        if (response.ok) {
            alert('下单成功');
            cart = []; // 清空购物车
            renderCart();
            await fetchOrders();
            renderOrders();
        } else {
            alert('下单失败');
        }
    });

    // 渲染订单列表
    function renderOrders() {
        const orderList = document.getElementById('order-list');
        orderList.innerHTML = ''; // 清空现有内容

        orders.forEach(order => {
            const orderItem = document.createElement('li');
            orderItem.className = 'list-group-item';

            orderItem.innerHTML = `
                    订单 ID: ${order.id} - 状态: ${order.status}
                `;

            orderList.appendChild(orderItem);
        });
    }

    // 设置 WebSocket 连接
    function setupWebSocket() {
        const ws = new WebSocket('ws://127.0.0.1:2346');
        ws.onmessage = (event) => {
            const message = JSON.parse(event.data);
            const order = orders.find(o => o.id === message.order_id);
            if (order) {
                order.status = message.status;
                renderOrders();
            }
        };
    }
</script>
</body>
</html>